; 递归
(define (accumlate combiner null-value term a next b)
    (if (> a b)
        null-value
        (combiner (term a)
            (accumlate combiner null-value term (next a) next b)
        )
    )
)

(define (product term a next b)
    (accumlate * 1 term a next b)
)

(define (factorial n)
    (define (add_1 x)
        (+ 1 x))
    (product * 1 add_1 n )
)
; 测试 product
(display (factorial 5))
(newline)

(define (sum term a next b)
    (accumlate + 0 term a next b)
)


(define (addsum n)
    (define (add_1 x)
        (+ 1 x))
    (sum + 1 add_1 n )
)
; 测试 sum
(display (addsum 5))
(newline)

; 迭代
(define (accumlate-iter combiner null-value term a next b)
    (define (iter n result)
        (if (> n b)
            result            
            (iter   (next n)
                    (combiner result
                        (term n)
                    )                 
            )
        )
    )
    (iter a null-value)
)

(define (product-iter term a next b)
    (accumlate-iter * 1 term a next b)
)

(define (factorial-iter n)
    (define (add_1 x)
        (+ 1 x))
    (product-iter * 1 add_1 n )
)
; 测试 product
(display (factorial-iter 5))
(newline)

(define (sum-iter term a next b)
    (accumlate-iter + 0 term a next b)
)


(define (addsum-iter n)
    (define (add_1 x)
        (+ 1 x))
    (sum-iter + 1 add_1 n )
)
; 测试 sum
(display (addsum-iter 5))

(exit)
